import React from 'react'

function Scroller(props) {
  // 停止滚动时显示滚动条的功能
  const [scrollTop, setScrollTop] = React.useState(0)
  const [scrollEnd, setScrollEnd] = React.useState(true)
  const scrollRef = React.useRef()
  let timeout = null
  const onScrollHandle = () => {
    if (scrollEnd !== false) {
      setScrollEnd(false)
    }
    if (timeout) {
      clearTimeout(timeout)
    }
    timeout = setTimeout(() => {
      if (scrollEnd !== true) {
        setScrollEnd(true)
        setScrollTop(scrollRef.current?.scrollTop || 0)
      }
    }, 200)
  }

  return (
    <div
      className={`feed-list scroller ${scrollEnd ? '' : 'scrolling'}`}
      ref={scrollRef}
      onScrollCapture={() => onScrollHandle()}
    >
      {React.Children.map(props.children, (child, i) => {
        // 增加一些滚动控制方法属性给子组件
        return React.cloneElement(child, {
          // scrollTop,
          setScrollTop,
          // setScrollEnd,
          // scrollRef,
        })
      })}
    </div>
  )
}

export default Scroller
